package com.deuwise.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.deuwise.common.utils.R;
import com.deuwise.common.utils.Result;

import com.deuwise.common.utils.cache.Cache;
import com.deuwise.system.entity.BackUpDo;
import com.deuwise.system.service.BackUpDoService;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.baomidou.mybatisplus.plugins.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

/**
 *@author deuwise
 *@date 2018-11-14 11:26:52
 */
@Api(tags = "数据库备份模块", description = "数据库备份模块")
@RequestMapping("api/backup")
@RestController()
public class BackUpDoController extends  AbstractController {
    @Autowired
    private BackUpDoService backUpDoService;


    @ApiOperation(value = "数据库备份list", notes = "数据库备份list")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("sys:backup:list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "文件名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "开始页数", defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", defaultValue = "15", dataType = "int", paramType = "query")})
    public Result<Page<BackUpDo>> getList(String name){
       Wrapper<BackUpDo> wrapper=new EntityWrapper<>();
       if(StringUtils.isNotBlank(name)){
           wrapper.like("name",name);
       }
        wrapper.orderBy("create_time",false);
        Page<BackUpDo> backUpDoPage = backUpDoService.selectPage(getPage(BackUpDo.class),wrapper);
        return Result.ok(backUpDoPage);
    }
    @ApiOperation(value = "下载备份")
    @GetMapping("/download/{id}")
    @RequiresPermissions("sys:backup:down")
    public void downBackUp(@PathVariable("id") String id,HttpServletResponse response,
                            HttpServletRequest request) throws IOException {
        BackUpDo backUpDo= backUpDoService.selectById(id);
        backUpDoService.downloadFile(response,backUpDo);

    }
    @ApiOperation(value = "数据库备份进度条", notes = "数据库备份进度条")
    @ResponseBody
    @RequestMapping(value = "/backUpProgress",method = RequestMethod.GET)
    public String flushProgress3(HttpServletRequest request) throws Exception
    {
        HashMap<String,Object> map=null;
        try {
            HttpSession session = request.getSession();
            map=new HashMap<String, Object>();
            //总条数
            map.put("totalCount",request.getSession().getAttribute("totalCount"));
            //已导条数
            map.put("curCount", request.getSession().getAttribute("curCount"));
            //百分比数字
            map.put("percent", request.getSession().getAttribute("percent"));
            map.put("percentText", request.getSession().getAttribute("percentText"));
            //百分比文本
            /// System.out.println(map.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(map);
    }

    @ApiOperation(value = "备份操作")
    @RequestMapping(value = "", method = RequestMethod.POST)
    @RequiresPermissions("sys:backup:save")
    public R save(HttpServletRequest request){
        boolean isSuccess = false;
        BackUpDo backUpDo=new BackUpDo();
        String backUrl="";
        if(Cache.get("backUpData")!=null){
            return R.error(200,"有备份任务进行中请稍后");
        }
        try {
            /**
             * 30分钟后自动过期
             */
            Cache.add("backUpData",1,1800000);
            backUrl=backUpDoService.backupData(request);
        } catch (IOException e) {
            Cache.remove("backUpData");
            e.printStackTrace();
            return  R.error();
        } catch (SQLException e) {
            Cache.remove("backUpData");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            Cache.remove("backUpData");
            e.printStackTrace();
            return  R.error();
        }
        Cache.remove("backUpData");
        backUpDo.setBackUrl(backUrl);
        backUpDo.setSizeNum(0);
        backUpDo.setFileType(0);
        if(StringUtils.isNotBlank(backUrl)) {
            backUpDoService.setBackUpData(backUpDo,backUrl);
        }
        backUpDo.setCreateTime(new Date());
        if(null == backUpDo){
            Cache.remove("backUpData");
            return R.error(200,"新增数据失败，请稍后再试!");
        }
        isSuccess = backUpDoService.insert(backUpDo);
        if (isSuccess) {
            return R.ok();
        } else {
            return R.error(200,"新增数据失败，请稍后再试!");
        }
    }
    @ApiOperation("删除备份")
    @DeleteMapping("/{id}")
    @RequiresPermissions("sys:backup:delete")
    public R delete(@PathVariable("id") String id){
      BackUpDo backUpDo=backUpDoService.selectById(id);
       boolean result=backUpDoService.deleteById(id);
       if(result) {
           if(backUpDo!=null) {
               File file = new File(backUpDo.getBackUrl());
               if (file != null && file.exists()) {
                   file.delete();
               }
           }
       }
        return R.ok();
    }


    @ApiOperation(value = "批量删除记录")
    @RequestMapping(value = "/deleteSelect", method = RequestMethod.POST)
    @RequiresPermissions("sys:backup:delete")
    public  R deleteSelect(@ApiParam(value = "ids集合",name = "ids",required = true) @RequestParam String[] ids){
        try {
            if (ids != null && ids.length > 0) {
                    backUpDoService.deleteBatchIds(Arrays.asList(ids));
            }
        }catch (Exception ex){
            return  R.error("删除失败");
        }
        return  R.ok();
    }

}